package com.usian.comment.service.impl;

import com.sun.xml.bind.v2.model.core.ID;
import com.usian.comment.feign.UserFeign;
import com.usian.comment.service.CommentService;
import com.usian.common.aliyun.GreeTextScan;
import com.usian.model.comment.dtos.CommentDto;
import com.usian.model.comment.dtos.CommentLikeDto;
import com.usian.model.comment.dtos.CommentSaveDto;
import com.usian.model.comment.vo.ApCommentVo;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.common.pojos.ApComment;
import com.usian.model.common.pojos.ApCommentLike;
import com.usian.model.user.pojos.ApUser;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserFeign userFeign;

    @Autowired
    private GreeTextScan greeTextScan;

    @Override
    public ResponseResult saveComment(CommentSaveDto dto) {
        //参数校验
        if (dto.getArticleId() == null || dto.getContent() == null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU);
        }
        //评论字数校验
        if (dto.getContent().length()>141){
            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"评论字数不能超过140字");
        }
        //评论文本审核校验
        boolean textScanBoolean = handleTextScan(dto.getContent());
        if (!textScanBoolean){
            return ResponseResult.errorResult(AppHttpCodeEnum.NULL_CANSHU,"评论内容不健康");
        }
        //用户登录校验
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"请登录");
        }else {
            //保存评论
            ApComment apComment = new ApComment();
            apComment.setAuthorId(apUser.getId());
            apComment.setAuthorName(apUser.getName());
            apComment.setContent(dto.getContent());
            apComment.setEntryId(dto.getArticleId());
            apComment.setCreatedTime(new Date());
            apComment.setUpdatedTime(new Date());
            apComment.setImage(apUser.getImage());
            apComment.setLikes(0);
            apComment.setReply(0);
            apComment.setType((short) 0);
            apComment.setFlag((short) 0);
            mongoTemplate.insert(apComment);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {
        //检查参数
        if (dto.getCommentId() == null ||(dto.getOperation()<0 && dto.getOperation()>1)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //判断是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"请登录");
        }
        //点赞操作
        Query query = Query.query(Criteria.where("_id").is(dto.getCommentId()));
        List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
        if (apComments.size()==0){
            return null;
        }
        ApComment apComment = apComments.get(0);
        if (apComment !=null && dto.getOperation()==0){
            //更新评论的点赞数量
            apComment.setLikes(apComment.getLikes() + 1);
            mongoTemplate.save(apComment);

            //保存 APP评论信息点赞
            ApCommentLike apCommentLike = new ApCommentLike();
            apCommentLike.setAuthorId(user.getId());
            apCommentLike.setCommentId(apComment.getId());
            apCommentLike.setOperation(dto.getOperation());
            mongoTemplate.save(apCommentLike);
        }else if (apComment !=null && dto.getOperation()==1){
            //4.取消点赞
            //更新评论的点赞数量
            apComment.setLikes(apComment.getLikes() < 0 ? 0 : apComment.getLikes() - 1);
            mongoTemplate.save(apComment);
            //更新 APP评论信息点赞
            mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentId").is(apComment.getId())),ApCommentLike.class);
        }
        //5.数据返回
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("likes",apComment.getLikes());
        return ResponseResult.okResult(resultMap);
    }

    @Override
    public ResponseResult findByArticleId(CommentDto dto) {
        //1.检查参数
        if(dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        int size = 10;

        //2.按照文章id过滤，设置分页和排序
//        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(dto.getMinDate()));
        //调试时间00
        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("createdTime").lt(new Date()));
        query.limit(size).with(Sort.by(Sort.Direction.DESC,"createdTime"));
        List<ApComment> list = mongoTemplate.find(query, ApComment.class);

        //3.数据封装返回
        //3.1 用户未登录 加载数据
        ApUser user = AppThreadLocalUtils.getUser();
        if(user== null){
            return ResponseResult.okResult(list);
        }

        //3.2 用户已登录，加载数据，需要判断当前用户点赞了哪些评论
//        List<String> idList =new ArrayList<>();
//        for (ApComment apComment : list) {
//            idList.add(apComment.getId());
//        }
        List<String> idList = list.stream().map(x -> x.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentId").in(idList).and("authorId").is(user.getId()));
        List<ApCommentLike> apCommentLikes = mongoTemplate.find(query1, ApCommentLike.class);

        List<ApCommentVo> resultList = new ArrayList<>();

        if(list!=null && apCommentLikes!=null){
            list.stream().forEach(x -> {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(x, apCommentVo);
                for (ApCommentLike apCommentLike : apCommentLikes) {
                    if (x.getId().equals(apCommentLike.getCommentId())) {
                        apCommentVo.setOperation((short) 0);
                        break;
                    }
                }
                resultList.add(apCommentVo);
            });

            return ResponseResult.okResult(resultList);
        }else {
            return ResponseResult.okResult(list);
        }
    }

    //评论审核
    private boolean handleTextScan(String content){
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            //审核不通过
            if (!map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }
}
